import { Component, Input, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, ValidationErrors, Validators } from '@angular/forms';
import { Observable, Observer } from 'rxjs';
import { Outlay } from 'src/app/models/outlay';

@Component({
  selector: 'app-outlay-modify',
  templateUrl: './outlay-modify.component.html',
  styleUrls: ['./outlay-modify.component.scss']
})
export class OutlayModifyComponent implements OnInit {

  @Input() aValue: Outlay = {
    name: '',
    type: '',
    money: '',
    time: '',
    mark: ''
  };
  labelSpan = 24;
  contSpan = 24;
  validateForm: FormGroup = new FormGroup({});
  typeList = [
    { label: '吃饭', value: '吃饭' },
    { label: '衣服', value: '衣服' },
    { label: '娱乐', value: '娱乐' },
    { label: '教育', value: '教育' },
    { label: '还贷', value: '还贷' },
  ]

  constructor(private fb: FormBuilder) {
    this.validateForm = this.fb.group({
      name: [
        '',
        [
          Validators.required,
          (c: FormControl): { [s: string]: boolean } => {
            return c.value.length > 128 ? { len128: true } : {};
          }
        ],
        // [this.nameRepeatAsyncValidator]
      ],
      type: ['', [Validators.required]],
      money: ['', [Validators.required]],
      time: [null, [Validators.required]],
      mark: ['']
    });
  }

  ngOnInit(): void {
    this.validateForm.patchValue({
      ...this.aValue,
      time: this.aValue && this.aValue.time ? new Date(this.aValue.time) : new Date(),
    });
  }

  verify() {
    for (const key in this.validateForm.controls) {
      if (this.validateForm.controls.hasOwnProperty(key)) {
        this.validateForm.controls[key].markAsDirty();
        this.validateForm.controls[key].updateValueAndValidity();
      }
    }
  }

  resetForm(e: MouseEvent): void {
    e.preventDefault();
    this.validateForm.reset();
    for (const key in this.validateForm.controls) {
      if (this.validateForm.controls.hasOwnProperty(key)) {
        this.validateForm.controls[key].markAsPristine();
        this.validateForm.controls[key].updateValueAndValidity();
      }
    }
  }

  nameRepeatAsyncValidator = (control: FormControl) =>
    new Observable((observer: Observer<ValidationErrors | null>) => {
      setTimeout(() => {
        if (control.value === 'admin') {
          // you have to return `{error: true}` to mark it as an error event
          observer.next({ error: true, admin: true });
        } else {
          observer.next(null);
        }
        observer.complete();
      }, 1000);
    });

}
